package com.micookie.v2ex.ui.fragment;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.view.ViewGroup;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.micookie.v2ex.App;
import com.micookie.v2ex.R;
import com.micookie.v2ex.api.APIConfig;
import com.micookie.v2ex.api.HttpRequest;
import com.micookie.v2ex.greendao.gen.NodeDao;
import com.micookie.v2ex.model.bean.Node;
import com.micookie.v2ex.ui.adapter.NodeListAdapter;
import com.micookie.v2ex.ui.base.BaseFragment;
import com.micookie.v2ex.ui.weight.SpacesItemDecoration;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * Created by Administrator on 2017-01-03.
 */

public class NodeListFragment extends BaseFragment {
    private static final String TAG = "NodeListFragment";

    @BindView(R.id.node_list_rv)
    RecyclerView mNodeListRecycle;

    @BindView(R.id.node_list_srl)
    SwipeRefreshLayout mSwipeRefresh;

    NodeListAdapter mNodeListAdapter;

    List<Node> mNodeList = new ArrayList<>();

    private static final int MSG_PULL_START = 0x01;

    private static final int MSG_PULL_STOP = 0x02;


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_node_list, container, false);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        inflater.inflate(R.menu.node_list_menu, menu);

    }

    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MSG_PULL_START:
                    mSwipeRefresh.setRefreshing(true);
                    break;
                case MSG_PULL_STOP:
                    mSwipeRefresh.setRefreshing(false);

                    mNodeListAdapter.getDataList().clear();
                    mNodeListAdapter.getDataList().addAll(mNodeList);

                    mNodeListAdapter.notifyDataSetChanged();
                    break;
            }
        }
    };


    @Override
    public void initData() {
        super.initData();
        loadData(false);
    }

    @Override
    public void initListener() {
        super.initListener();
        mSwipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                loadData(true);
            }
        });
    }

    private void loadNetData() {
        Log.d(TAG, "loadNetData() called, 通过网络加载");
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpRequest.getInstance().get(APIConfig.getAllNodeUrl(), new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        loadData(false);
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        String json = response.body().string();
                        List<Node> nodeList = new Gson().fromJson(json, new TypeToken<List<Node>>() {
                        }.getType());

                        mNodeList = nodeList;
                        mHandler.sendEmptyMessage(MSG_PULL_STOP);
                        saveNodeListData2Db(nodeList);
                    }
                });

            }
        }).start();
    }


    @Override
    public void initView() {
        super.initView();

        mSwipeRefresh.setColorSchemeResources(
                R.color.refresh_progress_1,
                R.color.refresh_progress_2,
                R.color.refresh_progress_3
        );

        //设置瀑布流布局
        mNodeListRecycle.setLayoutManager(new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL));
        mNodeListRecycle.addItemDecoration(new SpacesItemDecoration(getResources().getDimensionPixelSize(R.dimen.topic_list_item_decoration)));
        mNodeListAdapter = new NodeListAdapter(getActivity(), mNodeList);
        mNodeListRecycle.setAdapter(mNodeListAdapter);
    }


    /**
     * 加载数据
     *
     * @param isLoadNet 是否刷新网络数据
     */
    private void loadData(boolean isLoadNet) {
        mHandler.sendEmptyMessage(MSG_PULL_START);
        if (isLoadNet) {
            loadNetData();
        } else {
            readNodeListData();
        }


    }

    /**
     * 写入数据库
     *
     * @param nodeList
     */
    private void saveNodeListData2Db(final List<Node> nodeList) {
        if (nodeList == null || nodeList.isEmpty()) {
            return;
        }
        Log.d(TAG, "saveNodeListData() called 写入到数据库 nodeList.size() = :" + nodeList.size());
        new Thread(new Runnable() {
            @Override
            public void run() {
                NodeDao nodeDao = App.getInstance().getDaoSession().getNodeDao();
                nodeDao.deleteAll();
                nodeDao.insertInTx(nodeList);
            }
        }).start();
    }

    /**
     * 从数据库读取数据
     *
     * @return
     */
    private List<Node> readNodeListData() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                NodeDao nodeDao = App.getInstance().getDaoSession().getNodeDao();
                List<Node> dbNodeList = nodeDao.queryBuilder().build().list();
                if (dbNodeList == null || dbNodeList.isEmpty()) {
                    Log.d(TAG, "--readNodeListData--数据库读取为空,尝试网络加载");
                    //如果数据库返回为空,进行网络加载
                    loadNetData();
                    return;
                } else {
                    Log.d(TAG, "--readNodeListData--数据库读取到：" + dbNodeList.size());
                    mNodeList = dbNodeList;
                }
                mHandler.sendEmptyMessage(MSG_PULL_STOP);
            }
        }).start();
        return null;
    }
}
